<?php
namespace App\Base\Repositories;
use App\Base\Contracts\PublicInterface;
use App\Base\Models\PictureModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/6/8 0008
 * Time: 21:05
 */
class DbPublicRepository implements PublicInterface
{
    public function savePicture($file){
        $realPath = $file->getRealPath();
        $ext = $file->getClientOriginalExtension();
        $md5=md5_file($realPath);     //图片md5
        $sha1=sha1_file($realPath);
        $info=PictureModel::where("md5",$md5)->first();   //图片已上传过就返回数据
        if($info){
            return $info;
        }
        // 上传文件
        $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
        // 使用我们新建的uploads本地存储空间（目录）
        $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
        if($bool){
            $filePath = public_path('uploads')."/".$filename;
            if(get_config_param_value("QINIU_UPLOAD_IS_STATUS")){  //是否开启七牛上传
                //上传到七牛上去
                $accessKey =config("lzy.QINIU_ACCESS_KEY");
                $secretKey = config("lzy.QINIU_SECRET_KEY");
                $bucket = config("lzy.QINIU_BUCKET");
                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 生成上传 Token
                $token = $auth->uploadToken($bucket);
                // 要上传文件的本地路径

                // 上传到七牛后保存的文件名
                $key = $md5;
                // 初始化 UploadManager 对象并进行文件的上传。
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传。

                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                $token=config("lzy.QINIU_DOMAIN")."/".$ret['key'];
            }else{
                $token='';
            }


            $data=array(
                'path'=>'/uploads/'.$filename,
                'md5'=>$md5,
                'sha1'=>$sha1,
                'create_time'=>time(),
                'token'=>$token
            );

            //添加到数据表并且返回
            if($fileid=PictureModel::insertGetId($data)){
                //返回七牛token
                $data["id"]=$fileid;
                return $data;
            }else{
                return false;
            }

        }else{
            return false;
        }
    }
}